package ServiceCSV

import (
	"bufio"
	"encoding/csv"
	"github.com/tealeg/xlsx"
	"log"
	"mime/multipart"
	"ustcLab/server/dao/bean"
)

func ProcessCSV(recFile *multipart.FileHeader) ([]*bean.TripleData, error) {
	res := make([]*bean.TripleData, 0)

	file, err := recFile.Open()
	if err != nil {
		return nil, err
	}
	defer file.Close()
	reader := csv.NewReader(bufio.NewReader(file))
	for {
		line, err := reader.Read()

		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			return nil, err
		}
		//提取三元组关系：A is a B
		if line == nil || len(line) < 2 {
			return nil, err
		}
		res = append(res, &bean.TripleData{
			Substance: line[0],
			Relation:  line[1],
			Object:    line[2],
		})
	}
	return res, nil
}

/*
	根据医院对接的数据格式，定义的新版处理函数入口
*/
func ProcessTableData(recFile *multipart.FileHeader) ([]*bean.TripleData, error) {

	file, err := recFile.Open()
	if err != nil {
		return nil, err
	}
	defer file.Close()

	content := make([]byte, 20000)
	n, err := bufio.NewReader(file).Read(content)
	if err != nil {
		return nil, err
	}
	log.Println("[ProcessTableData] read file size=", n)
	tripleData, err := excelParse(content)
	if err != nil {
		return nil, err
	}
	return tripleData, nil
}

/*
	excel解析函数
*/
func excelParse(fileStream []byte) ([]*bean.TripleData, error) {
	xlFile, err := xlsx.OpenBinary(fileStream)
	if err != nil {
		log.Println("[excelParse] parse fileStream failed.")
		return nil, err
	}
	//获取行数
	length := len(xlFile.Sheets[0].Rows)
	//开辟除表头外的行数的数组内存
	resourceArr := make([]*bean.TripleData, length-1)
	//遍历sheet
	for _, sheet := range xlFile.Sheets {
		//遍历每一行
		for rowIndex, row := range sheet.Rows {
			//跳过第一行表头信息
			if rowIndex == 0 {
				continue
			}
			if len(row.Cells) == 0 || row.Cells[0].String() == "" {
				continue
			}
			resourceArr[rowIndex-1] = &bean.TripleData{
				Substance: row.Cells[0].String(),
				Relation:  row.Cells[4].String(),
				Object:    row.Cells[2].String(),
			}
			log.Printf("[Level DEBUG][ExcelParse] A[%s] --%s--> B[%s]\n",
				row.Cells[0].String(), row.Cells[4].String(), row.Cells[2].String())
		}
	}
	return resourceArr, nil
}
